// pages/pointsShop/pointsShop.js
import Toast from '@vant/weapp/toast/toast';
const app = getApp()
const { getAllProducts, payStorePoints, getUserPoints, addProductToCart, getUserAllAddress, getBatteryBrandInfo } = require("../../utils/api");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      title: '积分商城',
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight
    },
    active:0,
    isPoup:false,
    maginTopHeight: app.globalData.maginTopHeight,
    list:['新品','周转','维护'],
    userInfo: null,
    products: [], // 用于存储商品数据
    shoppingCartIndex: 0,
    groupNum: 1,
    shopNum: 1,
    points: {},
    buyPopup: false,
    addressPopup: false, 
    address: [],
    activeAddressIndex: 0,
    search: {
      value: '',
    },
    brandPicker: {
      brand: [],
      selectedBrand: '',
      show: false
    },
  },

  onSelectItem(e) {
    const shoppingCartIndex = this.data.shoppingCartIndex;
    const pointConsumeIndex = e.currentTarget.dataset.index;
    let SelectedConsume = 0;
    const updatedPonitConsume = this.data.products[shoppingCartIndex].ponitConsume.map((item, index) => {
      if (index === pointConsumeIndex) {
        SelectedConsume = item.points
        return {
          ...item, // 复制原有属性
          checked: true // 更新 Checked 属性
        };
      } else {
        return {
          ...item,
          checked: false
        };
      }
    });
    const PonitConsumePath = 'products[' + shoppingCartIndex + '].ponitConsume';
    const SelectedConsumePath = 'products[' + shoppingCartIndex + '].selectedConsume'
    this.setData({
      [PonitConsumePath]: updatedPonitConsume,
      [SelectedConsumePath]: SelectedConsume
    });
  },

  onLoad: function (options) {
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
    getAllProducts({
      PhoneNumber: this.data.userInfo.phoneNumber
    }).then(res => {
      if (res.code === 4004000) {
        const products = res.data.map(item => {
          let newItem = { ...item, hidden: false };
          newItem.ponitConsume = [
            {
              typeName: '新品',
              points: item.newBatteryPoints,
              checked: true
            },
            {
              typeName: '周转',
              points: item.turnOverPoints,
              checked: false
            },
            {
              typeName: '维护',
              points: item.maintenancePoints,
              checked: false
            }
          ];
          newItem.shopNum = 1;
          newItem.selectedConsume = item.newBatteryPoints;
          delete newItem.newBatteryPoints;
          delete newItem.turnOverPoints;
          delete newItem.maintenancePoints;
          return newItem;
        })
        this.setData({
          products: products
        });
        console.log(res);
      } else {
        console.log('请求失败，错误码：', res.code);
      }
    });

    getBatteryBrandInfo({
      PhoneNumber: this.data.userInfo.phoneNumber
    }).then(res => {
      if(res.code === 4008000) {
        const result = res.data.map(item => item.batteryBrand)
         this.setData({
           'brandPicker.brand': result,
           'brandPicker.selectedBrand': result[0]
         })
      }else {
        wx.showToast({
          title: '电池品牌获取失败！请联系管理员。',
          icon: 'none'
        })
      }
    });
  },

  shopNumChange(event) {
    this.setData({
      shopNum: event.detail
    });
  },

  groupNumChange(event) {
    this.setData({
      groupNum: event.detail
    });
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },

  buyGoods() {
    const data = { PhoneNumber: this.data.userInfo.phoneNumber,
      ProductNumber: this.data.products[this.data.shoppingCartIndex].productNumber,
      BuyWay: this.data.products[this.data.shoppingCartIndex].ponitConsume.filter(item => item.checked === true).map(item => item.typeName), 
      Size: this.data.shopNum,
      Address: this.data.address[this.data.activeAddressIndex].address,
      UserName: this.data.address[this.data.activeAddressIndex].userName,
      UserPhoneNumber: this.data.address[this.data.activeAddressIndex].userPhoneNumber,
      Package: this.data.groupNum,
      BatteryBrand: this.data.brandPicker.selectedBrand
    };
    payStorePoints(data).then(res =>{
      if (res.code == 4006010) {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
      this.buyPopupClose();
    })
  },

  addProductToCart() {
    const data = { PhoneNumber: this.data.userInfo.phoneNumber,
      ProductNumber: this.data.products[this.data.shoppingCartIndex].productNumber,
      BuyWay: this.data.products[this.data.shoppingCartIndex].ponitConsume.filter(item => item.checked === true).map(item => item.typeName), 
      Size: this.data.shopNum,
      Package: this.data.groupNum,
      Points: parseFloat(this.data.products[this.data.shoppingCartIndex].ponitConsume.find(item => item.checked).points) * this.data.shopNum,
      BatteryBrand: this.data.brandPicker.selectedBrand};
      addProductToCart(data).then(res =>{
      if (res.code == 4005000) {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
      this.buyPopupClose();
    })
  },

  buyPopupOpen(event) {
    const data = { PhoneNumber: this.data.userInfo.phoneNumber, };
    this.setData({
      buyPopup: true,
      shoppingCartIndex: event.currentTarget.dataset.index,
    });
    getUserPoints(data).then(res => { 
      if (res.code == 4003000) {
        this.setData({
          points: res.data,
        });
      }
    });
    this.getUserAllAddress()
  },

  buyPopupClose() {
    this.setData({
      buyPopup: false
    })
  },

  getUserAllAddress() {
    getUserAllAddress({PhoneNumber: this.data.userInfo.phoneNumber}).then(res => {
      if (res.code === 4007010) {
        let activeAddressIndex = 0;
        const address = res.data.map((item,index) =>{
          if (item.Default === 1) { activeAddressIndex = index }
          return{
            ...item,
            checked: false
          }
        })
        this.setData({
          address: address,
          activeAddressIndex: activeAddressIndex
        })
        if (address.length === 0) {
          this.setData({
            'address[0].Address': "暂无地址，请点此跳转至新增页面。"
          })
        }
      } else {
        wx.showToast({
          title: '地址获取失败' + res.msg,
        })
      }
    });
  },
  addressOpen() {
    if (this.data.address[0].Address === "暂无地址，请点此跳转至新增页面。") {
      wx.redirectTo({
        url: '/pages/address/address?addNewAddressPopup=true',
      })
      return
    }
    this.setData({
      addressPopup: true
    })
  },

  addressClose() {
    this.setData({
      addressPopup: false
    })
  },

  activeAddress(e) {
    this.setData({
      activeAddressIndex: e.currentTarget.dataset.index
    })
  },

  searchBarOnChange(e) {
    this.setData({
      'search.value': e.detail,
    });
  },

  searchBarOnSearch() {
    const text = this.data.search.value; // 获取搜索框的值
    const products = this.data.products;
  
    // 遍历数组并根据条件设置 hidden 属性
    products.forEach(item => {
      if (text === '') {
        item.hidden = false;
      } else {
        // 如果 BatteryUnite 存在且包含搜索文本，则显示该项
        let regex = new RegExp(text, 'i');
        if (item.productType && regex.test(item.productType)) {
          item.hidden = false;
        } else {
          item.hidden = true;
        }
      }
    });
    this.setData({
      products: products
    });
  },
  brandPickerOpen() {
    this.setData({
      'brandPicker.show': true
    })
  },
  brandPickerClose() {
    this.setData({
      'brandPicker.show': false
    })
  },
  brandConfirm(event) {
    const { picker, value, index } = event.detail;
    this.setData({
      'brandPicker.selectedBrand': value
    })
    this.brandPickerClose();
  },
})